//
//  LoginViewController.m
//  lvtu
//
//  Created by Apple on 12-3-8.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "wxAppDelegate.h"
#import "BaseDataSource.h"
#import "UserInfo.h"
#import "DataSource.h"
#import <QuartzCore/QuartzCore.h>

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.delegate = self;
    
    backgroundScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    backgroundScrollView.backgroundColor = [UIColor whiteColor];
    backgroundScrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height+180);
    
    backgroundScrollView.pagingEnabled = NO;
    backgroundScrollView.scrollEnabled = NO;
    backgroundScrollView.clipsToBounds = YES;
    backgroundScrollView.scrollsToTop = YES;
    backgroundScrollView.showsVerticalScrollIndicator = NO;
    backgroundScrollView.showsHorizontalScrollIndicator = NO;
    backgroundScrollView.delegate = self;
    [self.view addSubview:backgroundScrollView];
    
    UIImage * background_image = [UIImage imageNamed:@"bg_texture.png"];
    UIButton * backgroundButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backgroundButton setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [backgroundButton setBackgroundImage:background_image forState:UIControlStateNormal];
    [backgroundButton setBackgroundImage:background_image forState:UIControlStateHighlighted];
    [backgroundButton addTarget:self action:@selector(backgroundButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [backgroundScrollView addSubview:backgroundButton];
    [backgroundButton setBackgroundColor:[UIColor grayColor]];
    
    //创建背景图片
//    UIImageView* backgroudImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//    backgroudImageView.image = [UIImage imageNamed:@"bg_texture.png"];
//    [backgroundScrollView addSubview:backgroudImageView];
//    [backgroudImageView release];
    
    //创建封面图片
    UIImageView* coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 226)];
    coverImageView.image = [UIImage imageNamed:@"login_logo.png"];
    [backgroundScrollView addSubview:coverImageView];
    [coverImageView release];
    
    //创建输入框
    inputView = [[UIImageView alloc] initWithFrame:CGRectMake(4, 249, self.view.frame.size.width - 8, 99)];
    UIImage* stretchImg = [[UIImage imageNamed:@"bg_whiteframe.png"] stretchableImageWithLeftCapWidth:30 topCapHeight:20];
    inputView.image = stretchImg;    
    inputView.clipsToBounds = YES;
    inputView.userInteractionEnabled = YES;
    [backgroundScrollView addSubview:inputView];
    
    UIImageView* lineView = [[UIImageView alloc] initWithFrame:CGRectMake(27, inputView.frame.size.height/2-6, inputView.frame.size.width-54, 1)];
    lineView.backgroundColor = [UIColor colorWithRed:218/255.0 green:219/255.0 blue:211/255.0 alpha:1.0];
    [inputView addSubview:lineView];
    [lineView release];
    
    UILabel* accountLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 6, 50, 35)];
    accountLabel.text = @"账号 ：";
    accountLabel.font = [UIFont systemFontOfSize:12];
    accountLabel.backgroundColor = [UIColor clearColor];
    [inputView addSubview:accountLabel];
    [accountLabel release];
    
    nameTextField = [[UITextField alloc] init];
//    UIImage* TextFieldImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_imput.png" ofType:nil]];
//    [nameTextField setBackground:TextFieldImage];
    [nameTextField setFrame:CGRectMake(75, 6, 200, 35)];
    //[nameTextField setBackgroundColor:[UIColor clearColor]];
    nameTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;                
    [nameTextField setAutocorrectionType:UITextAutocorrectionTypeDefault];
    [nameTextField setReturnKeyType:UIReturnKeyDefault];
    [nameTextField setFont:[UIFont boldSystemFontOfSize:13]];
    [nameTextField setDelegate:self];
    [nameTextField setTextColor:[UIColor grayColor]];
    [nameTextField setKeyboardType:UIKeyboardTypeEmailAddress];
    [nameTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [nameTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [nameTextField setClipsToBounds:YES];
    [inputView addSubview:nameTextField];
    
    UILabel* passwordLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, inputView.frame.size.height/2-4, 50, 35)];
    passwordLabel.text = @"密码 ：";
    passwordLabel.font = [UIFont systemFontOfSize:12];
    passwordLabel.backgroundColor = [UIColor clearColor];
    [inputView addSubview:passwordLabel];
    [passwordLabel release];
    
    passwdTextField = [[UITextField alloc] init];
    [passwdTextField setFrame:CGRectMake(75, inputView.frame.size.height/2-4, 200, 35)];
    [passwdTextField setBackgroundColor:[UIColor clearColor]];
    passwdTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;                
    [passwdTextField setAutocorrectionType:UITextAutocorrectionTypeDefault];
    [passwdTextField setReturnKeyType:UIReturnKeyDefault];
    [passwdTextField setFont:[UIFont boldSystemFontOfSize:13]];
    [passwdTextField setDelegate:self];
    [passwdTextField setTextColor:[UIColor grayColor]];
    [passwdTextField setKeyboardType:UIKeyboardTypeURL];
    [passwdTextField setSecureTextEntry:YES];
    [passwdTextField setClearButtonMode:UITextFieldViewModeWhileEditing];
    [passwdTextField setClipsToBounds:YES];
    [inputView addSubview:passwdTextField];
    
    emailView =[[WKEmailInputView alloc] initWithFrame:CGRectMake(75, 6+35, nameTextField.frame.size.width, 70)];
	emailView.userInteractionEnabled = YES;
    [[emailView layer] setBorderColor:[[UIColor lightGrayColor] CGColor]];
    [[emailView layer] setBorderWidth:1.0];
    [[emailView layer] setCornerRadius:4];
	emailView.delegate = self;
    
    [inputView release];
    //创建登录botton
    buttonlogin = [UIButton buttonWithType:UIButtonTypeCustom];
	buttonlogin.frame = CGRectMake(30, 353, 122, 40);
    [buttonlogin setBackgroundImage:[UIImage imageNamed:@"btn_done_normal.png"] forState:UIControlStateNormal];
    [buttonlogin setBackgroundImage:[UIImage imageNamed:@"btn_done_press.png"] forState:UIControlStateHighlighted];
	[buttonlogin setTitle:@"登录" forState:UIControlStateNormal];
    buttonlogin.titleLabel.font = [UIFont boldSystemFontOfSize:16];
	[buttonlogin addTarget:self action:@selector(loginButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[backgroundScrollView addSubview:buttonlogin];
    
    loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    loadingView.frame = CGRectMake(buttonlogin.frame.size.width/2-10, buttonlogin.frame.size.height/2-10, 20, 20);
    [buttonlogin addSubview:loadingView];
    
    //创建注册botton
    buttonSignUp = [UIButton buttonWithType:UIButtonTypeCustom];
	buttonSignUp.frame = CGRectMake(160, 353, 122, 40);
    [buttonSignUp setBackgroundImage:[UIImage imageNamed:@"btn_signup_normal.png"] forState:UIControlStateNormal];
    [buttonSignUp setBackgroundImage:[UIImage imageNamed:@"btn_signup_press.png"] forState:UIControlStateHighlighted];
	[buttonSignUp setTitle:@"注册 >>" forState:UIControlStateNormal];
    buttonSignUp.titleLabel.font = [UIFont boldSystemFontOfSize:16];
	[buttonSignUp addTarget:self action:@selector(signUpButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[backgroundScrollView addSubview:buttonSignUp];
    
    //创建找回密码button
    buttonFindOut = [UIButton buttonWithType:UIButtonTypeCustom];
	buttonFindOut.frame = CGRectMake(40, 418, 17, 17);
    [buttonFindOut setBackgroundImage:[UIImage imageNamed:@"btn_question_normal.png"] forState:UIControlStateNormal];
    [buttonFindOut setBackgroundImage:[UIImage imageNamed:@"btn_question_press.png"] forState:UIControlStateHighlighted];
	[buttonFindOut addTarget:self action:@selector(findOutButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[backgroundScrollView addSubview:buttonFindOut];
    
    UILabel* findOutLabel = [[UILabel alloc] initWithFrame:CGRectMake(62, 416, 80, 20)];
    findOutLabel.text = @"找回密码";
    findOutLabel.font = [UIFont boldSystemFontOfSize:12];
    findOutLabel.backgroundColor = [UIColor clearColor];
    [backgroundScrollView addSubview:findOutLabel];
    [findOutLabel release];
    
    UIButton* findButton = [UIButton buttonWithType:UIButtonTypeCustom];
	findButton.frame = CGRectMake(62, 416, 80, 20);
    [findButton setBackgroundColor:[UIColor clearColor]];
	[findButton addTarget:self action:@selector(findOutButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[backgroundScrollView addSubview:findButton];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidUnload
{
    [loadingView release], loadingView = nil;
    [emailView release], emailView = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    NSLog(@"test1");
    if ([viewController isKindOfClass:[LoginViewController class]]) {
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
    
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    NSLog(@"test2");
    
}

- (void)setEnableButton:(BOOL)b
{
    if (b)
    {
        buttonlogin.enabled = YES;
        buttonFindOut.enabled = YES;
        buttonSignUp.enabled = YES;
        [loadingView stopAnimating];
    }
    else
    {
        buttonlogin.enabled = NO;
        buttonFindOut.enabled = NO;
        buttonSignUp.enabled = NO;
        [loadingView startAnimating];
    }
}

- (void)login
{
    //martin.szj@gmail.com  123456
    NSString* psword = [[DataSource shareInstance] md5_hexDigest:passwdTextField.text];
    NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:nameTextField.text/*@"martin.szj@gmail.com"*/,@"email",
                          psword/*@"123456"*/,@"password",
                          [[DataSource shareInstance] sys_getOSVersion],@"os",
                          LVTU_CLIENT_VERSION,@"version",
                          LVTU_CHANNEL,@"channel",
                          [[DataSource shareInstance] sys_getDeviceModelName],@"device_name",
                          [[DataSource shareInstance] sys_getDeviceID],@"device_id",
                          @"1",@"is_iphone",
                          nil];
    CoreMsg* msg = [[CoreMsg alloc] init];
    msg.data = LOGININFO;
    msg.ui_delegate = self;
    
    [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_o_login" postInfo:info userInfo:msg];
    
    //    [[wxAppDelegate getAppDelegate] popAllViewController];
    //    [[wxAppDelegate getAppDelegate] showTabMainFrame]; 
}

- (void)loginButtonPressed:(id)sender
{    
    [self setEnableButton:NO];
    [passwdTextField resignFirstResponder];
    [nameTextField resignFirstResponder];
    
    [self performSelector:@selector(login) withObject:nil afterDelay:0.3f];
}

- (void)signUpButtonPressed:(id)sender
{
    //登录成功，进入主页面
    signViewController = [[SignUpViewController alloc] init];
    [self.navigationController pushViewController:signViewController animated:YES];
}

- (void)findOutButtonPressed:(id)sender
{
    //登录成功，进入主页面
    findOutViewController = [[FindOutViewController alloc] init];
    [self.navigationController pushViewController:findOutViewController animated:YES];
}

#pragma mark - WKEmailInputViewDelegate

- (void)emailSeleted:(NSString *)emailText
{
    nameTextField.text = emailText;
}

#pragma -mark DataSourceDelegate

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
    if ([coreMsg.data isEqual: LOGININFO]) {
        [wxAppDelegate getAppDelegate].isLogin = YES;
        [self setEnableButton:YES];
        [[DataSource shareInstance] saveUserStatusToKeyChain:nameTextField.text passwd:passwdTextField.text];
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = PERSONINFO;
        msg.ui_delegate = [wxAppDelegate getAppDelegate];
        
        [[NetDataSource shareInstance] postTo:@"http://www.wxlvtu.com/?a=page_personal_information" postInfo:nil userInfo:msg];
        
        //登录成功，进入主页面
        [[wxAppDelegate getAppDelegate] popAllViewController];
        [[wxAppDelegate getAppDelegate] showTabMainFrame];
    }
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    if ([coreMsg.data isEqual: LOGININFO]) {
        [self setEnableButton:YES];
        NSString* message;
        if ([data isKindOfClass:[NSString class]]) {
            if ([data isEqualToString:@"no_match"]) {
                message = @"登录名密码不匹配";
            }
            else {
                message = data;
            }
        }
        else {
            message = data;
        }
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 2001;
        [alert show];
        [alert release];
    }
}

#pragma -mark UITextFieldDelegate

- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary* userInfo = [notification userInfo];
    
    /*
     Restore the size of the text view (fill self's view).
     Animate the resize so that it's in sync with the disappearance of the keyboard.
     */
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    //[self moveInputBarWithKeyboardHeight:0.0 withDuration:animationDuration];
    [backgroundScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == nameTextField) {
        [backgroundScrollView setContentOffset:CGPointMake(0, 160) animated:YES]; 
    }
    else
    {
        [backgroundScrollView setContentOffset:CGPointMake(0, 160) animated:YES];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (!passwdTextField.isEditing && !nameTextField.isEditing ) {
        [passwdTextField resignFirstResponder];
        [nameTextField resignFirstResponder];
        //[backgroundScrollView setContentOffset:CGPointMake(0, 0) animated:YES]; 
    }
    [emailView closeEmailInfo];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (1 == range.length) {//按下回格键
        return YES;
    }
    
    if ([string isEqualToString:@"\n"])
    {//按下return键
        //这里隐藏键盘，不做任何处理
        [textField resignFirstResponder];
        //        [self willLoginWeibo];
        return NO;
    }
    else if (textField == nameTextField )
    {
        if ([string isEqual:@"@"]) 
        {
            [emailView setEmailInfo:textField.text];
            [inputView addSubview:emailView];
        }
        else 
        {
            NSRange range = [[textField.text stringByAppendingString:string] rangeOfString:@"@"];
            if (range.location != NSNotFound ) {
                [emailView reSetEmailInfo:[textField.text stringByAppendingString:string]];
                if (![emailView isDescendantOfView:backgroundScrollView]) {
                    [inputView addSubview:emailView];
                }
            }
            else
            {
                [emailView closeEmailInfo];
            }
        }
        return YES;
    }
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == nameTextField)
    {
        [nameTextField setText:@""];
        [nameTextField setTextColor:[UIColor grayColor]];
    }
    else if (textField == passwdTextField)
    {
        [passwdTextField setText:@""];
        [passwdTextField setTextColor:[UIColor grayColor]];
    }
    [emailView closeEmailInfo];
    return YES;
}

#pragma -mark  notify&button

- (void)backgroundButtonClick
{
    [nameTextField resignFirstResponder];
    [passwdTextField resignFirstResponder];
    [backgroundScrollView setContentOffset:CGPointMake(0, 0) animated:YES]; 
}
@end
